'use strict';

import Vue from 'vue';

/**
 * 货币自动转换
 * symbol: 货币符号
 * place：剩余小数位
 * @name currencyDisplay
 * @description : 双向过滤器
 */
Vue.filter('currencyDisplay', {
    // model -> view
    // 在更新 `<input>` 元素之前格式化值
    read: function(val,symbol,place) {
        if(val==''||_.isNil(val)){return ''}
        let numVal;

        if(val == undefined) return;

        if(isNaN(val)){
            numVal = Number(val.replace(/[^0-9-.]/g, ''));
        }

        else{
           numVal = Number(val);
        }
        return numVal.formatMoney( place,symbol);
    },
    // view -> model
    // 在写回数据之前格式化值
    write: function(val, oldVal) {

        if(val == undefined) return;

        let numVal = Number(val.replace(/[^0-9-.]/g, ''));

        oldVal =  Number(oldVal.replace(/[^0-9-.]/g, ''));

        if (numVal== 0)  return oldVal;

        else{
            return numVal;
        }
    }
});

/** 把数字转换为货币 */
Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "￥";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var number = this,
        negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};
